package com.quectel.cms.controller.parking;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.parking.ParkingOrderTreeVo;
import com.quectel.constant.core.parking.ParkingOrderConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.parking.dto.ParkingOrderDto;
import com.quectel.core.module.parking.service.ParkingOrderService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/04/13 11:16
 */
@RestController
@RequestMapping("parkingOrder")
@Tag(name = "ParkingOrderController", description = "停车场收费订单相关api")
public class ParkingOrderController extends BaseController {

    @DubboReference
    private ParkingOrderService parkingOrderService;

    /**
     * 导出历史停车记录
     */
    @GetMapping("exportParkExcel")
    @RequirePermissions(values = "parkingOrder:exportExcel")
    public void exportParkExcel(@RequestParam Map<String, Object> params, HttpServletResponse httpServletResponse) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        request.put(LambdaUtil.getFieldName(ParkingOrderDto::getStatus), ParkingOrderConstants.OrderStatusEnum.FINISHED.getStatus());
        request.put(ParkingOrderConstants.QUERY_BASE_ORDER_NAME, SystemConstants.COMMON.toString());

        List<ParkingOrderDto> result = PageFetchKit.fetchAll(r -> parkingOrderService.queryList(r), request.getParams());
        String[] headers = new String[]{"所属小区", "车牌号", "车牌颜色", "购卡情况", "所属人姓名", "所属人电话", "停车场名称","停车时长", "入场时间", "出场时间"};
        List<String[]> dataList = new ArrayList<>();

        for (ParkingOrderDto data : result) {
            String[] item = new String[headers.length];
            item[0] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : "";
            item[1] = data.getLicense();
            item[2] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.LICENSE_COLOR, data.getLicenseColor() + "");
            item[3] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_IS_PAY_CARD, data.getIsPayCard() + "");
            item[4] = Objects.nonNull(data.getCar()) ? data.getCar().getOwnerName() : "";
            item[5] = Objects.nonNull(data.getCar()) ? data.getCar().getOwnerMobile() : "";
            item[6] = data.getParkName();
            item[7] = data.getStayDuration();
            item[8] = data.getInTime() != null ? DateUtils.format(data.getInTime(), DateUtils.FormatType.COMMON) : null;
            item[9] = data.getOutTime() != null ? DateUtils.format(data.getOutTime(), DateUtils.FormatType.COMMON) : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(httpServletResponse, "历史停车记录", headers, dataList, "历史停车记录");

    }

    /**
     * 历史停车列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("parkList")
    @RequirePermissions(values = "parkingOrder:list")
    @Operation(summary = "历史停车列表")
    public Response<Page<ParkingOrderDto>> parkList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        request.put(LambdaUtil.getFieldName(ParkingOrderDto::getStatus), ParkingOrderConstants.OrderStatusEnum.FINISHED.getStatus());
        request.put(ParkingOrderConstants.QUERY_BASE_ORDER_NAME, SystemConstants.COMMON.toString());

        super.fillAuthorityData(request.getParams());
        int total = parkingOrderService.queryTotal(request.getParams());

        List<ParkingOrderDto> list = null;
        if (total > 0) {
            list = parkingOrderService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ParkingOrderDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ParkingOrderDto>>ok().wrap(page);
    }

    /**
     * 导出记录
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "parkingOrder:exportExcel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse httpServletResponse) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<ParkingOrderDto> result = PageFetchKit.fetchAll(r -> parkingOrderService.queryTreeList(r), request.getParams());
        List<ParkingOrderTreeVo> parkingOrderTreeVos = treeBuilder(result);

        String[] headers = new String[]{"车牌颜色", "车牌号码", "所属小区", "停车场名", "订单编号", "车主姓名", "车主电话", "停留时长"
                , "入场时间", "出场时间", "是否购卡", "应收金额", "实收金额", "支付方式", "支付状态", "支付时间", "压线时间", "完成状态", "创建时间"};
        List<String[]> dataList = new ArrayList<>();

        for (ParkingOrderTreeVo data : parkingOrderTreeVos) {
            String[] item = new String[headers.length];
            item[0] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.LICENSE_COLOR, data.getLicenseColor() + "");
            item[1] = data.getLicense();
            item[2] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : "";
            item[3] = data.getParkName();
            item[4] = data.getOrderNo();
            item[5] = data.getOwnerName();
            item[6] = data.getOwnerMobile();
            item[7] = data.getStayDuration();
            item[8] = Objects.nonNull(data.getInTime()) ? DateUtils.format(data.getInTime(), DateUtils.FormatType.COMMON) : "";
            item[9] = Objects.nonNull(data.getOutTime()) ? DateUtils.format(data.getOutTime(), DateUtils.FormatType.COMMON) : "";
            item[10] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_IS_PAY_CARD, data.getIsPayCard() + "");
            item[11] = Objects.nonNull(data.getDueAmount()) ? data.getDueAmount().toPlainString() : "";
            item[12] = Objects.nonNull(data.getPayAmount()) ? data.getPayAmount().toPlainString() : "";
            item[13] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_CARD_PAY_TYPE, data.getPayType() + "");
            item[14] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_PAY_STATUS, data.getPayStatus() + "");
            item[15] = Objects.nonNull(data.getPayTime()) ? DateUtils.format(data.getPayTime(), DateUtils.FormatType.COMMON) : "";
            item[16] = Objects.nonNull(data.getCrimpingTime()) ? DateUtils.format(data.getCrimpingTime(), DateUtils.FormatType.COMMON) : "";
            item[17] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_ORDER_STATUS, data.getStatus()+ "");
            item[18] = Objects.nonNull(data.getCreateTime()) ? DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON) : "";
            dataList.add(item);

            if (CollectionUtils.isNotEmpty(data.getChildren())) {
                for (ParkingOrderTreeVo child : data.getChildren()) {
                    String[] childItem = new String[headers.length];
                    childItem[0] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.LICENSE_COLOR, child.getLicenseColor() + "");
                    childItem[1] = child.getLicense();
                    childItem[2] = Objects.nonNull(child.getVillage()) ? child.getVillage().getName() : "";
                    childItem[3] = child.getParkName();
                    childItem[4] = child.getOrderNo();
                    childItem[5] = child.getOwnerName();
                    childItem[6] = child.getOwnerMobile();
                    childItem[7] = child.getStayDuration();
                    childItem[8] = Objects.nonNull(child.getInTime()) ? DateUtils.format(child.getInTime(), DateUtils.FormatType.COMMON) : "";
                    childItem[9] = Objects.nonNull(child.getOutTime()) ? DateUtils.format(child.getOutTime(), DateUtils.FormatType.COMMON) : "";
                    childItem[10] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_IS_PAY_CARD, child.getIsPayCard() + "");
                    childItem[11] = Objects.nonNull(child.getDueAmount()) ? child.getDueAmount().toPlainString() : "";
                    childItem[12] = Objects.nonNull(child.getPayAmount()) ? child.getPayAmount().toPlainString() : "";
                    childItem[13] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_PAY_TYPE, child.getPayType() + "");
                    childItem[14] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_PAY_STATUS, child.getPayStatus() + "");
                    childItem[15] = Objects.nonNull(child.getPayTime()) ? DateUtils.format(child.getPayTime(), DateUtils.FormatType.COMMON) : "";
                    childItem[16] = Objects.nonNull(child.getCrimpingTime()) ? DateUtils.format(child.getCrimpingTime(), DateUtils.FormatType.COMMON) : "";
                    childItem[17] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARKING_ORDER_STATUS, child.getStatus()+ "");
                    childItem[18] = Objects.nonNull(child.getCreateTime()) ? DateUtils.format(child.getCreateTime(), DateUtils.FormatType.COMMON) : "";
                    dataList.add(childItem);
                }
            }
        }
        POIUtils.exportExcel(httpServletResponse, "停车场订单", headers, dataList, "停车场订单");

    }

    /**
     * 分页树形列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("treeList")
    @RequirePermissions(values = "parkingOrder:list")
    @Operation(summary = "分页树形列表")
    public Response<Page<ParkingOrderTreeVo>> treeList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = parkingOrderService.queryTreeTotal(request.getParams());

        List<ParkingOrderDto> list = null;
        if (total > 0) {
            list = parkingOrderService.queryTreeList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ParkingOrderTreeVo> page = new Page<>(request.getPageNo(), request.getPageSize(), total, treeBuilder(list));
        return Response.<Page<ParkingOrderTreeVo>>ok().wrap(page);
    }

    private List<ParkingOrderTreeVo> treeBuilder(List<ParkingOrderDto> parkingOrderDtos) {
        List<ParkingOrderTreeVo> resp = new ArrayList<>();

        List<ParkingOrderTreeVo> deviceTreeVoList = CopyUtils.copyList(parkingOrderDtos, ParkingOrderTreeVo.class);
        for (ParkingOrderTreeVo c1 : deviceTreeVoList) {
            if (c1.getPreParkingOrderId() == null) {
                resp.add(c1);
            }
            for (ParkingOrderTreeVo c2 : deviceTreeVoList) {
                if (Objects.equals(c2.getPreParkingOrderId(), c1.getId())) {
                    if (c1.getChildren() == null) {
                        c1.setChildren(new ArrayList<>());
                    }
                    c1.getChildren().add(c2);
                }
            }
        }
        return resp;
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "parkingOrder:list")
    @Operation(summary = "分页列表")
    public Response<Page<ParkingOrderDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = parkingOrderService.queryTotal(request.getParams());

        List<ParkingOrderDto> list = null;
        if (total > 0) {
            list = parkingOrderService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ParkingOrderDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ParkingOrderDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "parkingOrder:edit")
    @Operation(summary = "查询单条记录")
    public Response<ParkingOrderDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (parkingOrderService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingOrderDto parkingOrderDto = parkingOrderService.selectById(id);

        return Response.<ParkingOrderDto>ok().wrap(parkingOrderDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "parkingOrder:info")
    @Operation(summary = "查询单条记录")
    public Response<ParkingOrderDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (parkingOrderService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingOrderDto parkingOrderDto = parkingOrderService.selectById(id);

        return Response.<ParkingOrderDto>ok().wrap(parkingOrderDto);
    }

    /**
     * 保存
     *
     * @param parkingOrderDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "parkingOrder:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated ParkingOrderDto parkingOrderDto) {

        //填充基础数据
        fillSaveCommonData(parkingOrderDto);

        parkingOrderService.save(parkingOrderDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param parkingOrderDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "parkingOrder:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated ParkingOrderDto parkingOrderDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(parkingOrderDto.getId()));
        if (parkingOrderService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(parkingOrderDto);

        parkingOrderService.updateById(parkingOrderDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "parkingOrder:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (parkingOrderService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        parkingOrderService.deleteBatch(ids);

        return Response.ok();
    }
}
